<?php
declare (strict_types=1);

namespace app\command;

use app\server\CallServer;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use \think\facade\Db;
use think\facade\Log;

class Exchange extends Command
{
    protected function configure()
    {
        // 指令配置
        $this->setName('exchange')
            ->setDescription('the check command');
    }

    protected function execute(Input $input, Output $output)
    {
        try {
            $this->exchange();
        } catch (\Exception $e) {
            addDebugLog('ExchangeLog', ['msg' => $e->getMessage()]);
            var_dump($e->getMessage());
        }
        $output->writeln('exchange');
    }


    public function exchange()
    {
        $now = time();
        $yesterdayTime = $now - 3600*24;
        $map = [
            ['update_at','>',date('Y-m-d 00:00:00',$yesterdayTime)],
            ['settle_at','<',strtotime(date('Y-m-d 00:00:00',$now))]
        ];
        $kyyUserTable = 'app_kyy_user';
        $list = simlist($kyyUserTable,'id,uuid,update_at', $map);
        $transcationTable = 'app_kyy_user_transcation';
        foreach($list as $user){
            $map = [
                'uuid'=>$user['uuid'],
                'ymd'=>date('Ymd',$yesterdayTime),
                'sub'=>'+'
            ];
            $totalCoins = (int)(Db::table($transcationTable)->where($map)->sum('coins'));
            if($totalCoins > 0){
                $money = number_format($totalCoins/10000*3.3,2);
                Db::table($kyyUserTable)->where(['id'=>$user['id']])->inc('money', (float)$money)->dec('coins',$totalCoins)->update();
                edit($kyyUserTable,['id'=>$user['id']],['settle_at'=>$now,'update_at'=>$user['update_at']]);
                $transcationNo = date('YmdHis',time()).mt_rand(1,9999999);
                $baseRow = [
                    'transcation_no'=>$transcationNo,
                    'uid'=>$user['id'],
                    'uuid'=>$user['uuid'],
                    'ymd'=>date('Ymd',$now)
                ];
                $coinsRow = $moneyRow = $baseRow;
                $coinsRow['coins'] = $totalCoins;
                $coinsRow['sub'] = '-';
                $coinsRow['type'] = 'exchange';
                $coinsRow['type_name'] = '金币自动兑换';
                add($transcationTable,$coinsRow);
                $moneyRow['money'] = $money;
                $moneyRow['type_name'] = "金币兑换";
                add('app_kyy_user_transcation_money',$moneyRow);
            }else{
                edit($kyyUserTable,['id'=>$user['id']],['settle_at'=>$now,'update_at'=>$user['update_at']]);
            }

        }
    }



}
